package com.atguigu.teach.mytask;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Ticket{
    //模拟50张票
    int num=50;
/*    private synchronized void sale(){
        if(num>0){
            System.out.println(Thread.currentThread().getName()+"\t"+"---卖出第："+(num--)+"张\t 还剩下："+num);
        }
    }*/
//=================================================================================================
   // private ReentrantLock lock=new ReentrantLock();
    private Lock lock= new ReentrantLock();
    public  void sale(){
                lock.lock();
                try{
                    if(num>0){
                        System.out.println(Thread.currentThread().getName()+"\t"+"---卖出第："+(num--)+"张\t 还剩下："+num);
                    }
                }catch (Exception e){

                }finally {
                    lock.unlock();
                }
    }
}

public class MySaleTicket {

   /* 1在高类聚低耦合的前提下，线程  操作 资源类*/
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                for (int i = 0; i <51 ; i++) {
//                 ticket.sale();
//                }
//            }
//        }, "a").start();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                for (int i = 0; i <51 ; i++) {
//                    ticket.sale();
//                }
//            }
//        }, "b").start();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                for (int i = 0; i <51 ; i++) {
//                    ticket.sale();
//                }
//            }
//        }, "c").start();

        //简化1
       /* new Thread(()->{
            for (int i = 0; i <51 ; i++) {
                ticket.sale();
            }
        },"a").start();
        new Thread(()->{
            for (int i = 0; i <51 ; i++) {
                ticket.sale();
            }
        },"b").start();
        new Thread(()->{
            for (int i = 0; i <51 ; i++) {
                ticket.sale();
            }
        },"c").start();*/
//        new Thread(()->{for(int i=0;i<51;i++) ticket.sale();},"a").start();
//        new Thread(()->{for(int i=0;i<51;i++) ticket.sale();},"b").start();
//        new Thread(()->{for(int i=0;i<51;i++) ticket.sale();},"c").start();
        //线程池买票
        ExecutorService threadpool = Executors.newFixedThreadPool(3);
        for (int i = 0; i <50 ; i++) {
            threadpool.execute(()->{ticket.sale();});
        }

    }
}
